#!/usr/bin/env php
<?php

/*
 * folder2dot
 *
 *     http://www.twisty.com/misc/folder2dot/
 *
 * A few URLs:
 *     Graphviz: http://www.research.att.com/sw/tools/graphviz/
 *     The Macintosh port of Graphviz: http://www.pixelglow.com/graphviz/
 *     GraphViz Site Map Generator: http://urlgreyhot.com/graphviz/
 *     Platypus: http://sveinbjorn.vefsyn.is/platypus
 */

/*
 * This script is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * The first useful argument (the dropped file) is $argv[1]
 */
$infile = $argv[1];
$infile = rtrim ($infile, '/');
$outfile = $infile . ".dot";

if (is_null ($infile))
{
	print (-1);
	exit;
}

if (!is_dir ($infile))
{
	print (-2);
	exit;
}

/*
 * Capture the results of recursive_dir function
 * because returning a result from the recursive function
 * was doing my head in. And I'm lazy.
 */
ob_start("capture");
print_r("0\t0\t" . basename($infile) . "\n");
recursive_dir($infile . "/", 0, 0);
ob_end_flush();
print (1);

/*
 * This is silly
 */
function capture($buffer)
{
	create_dot_file($buffer);
	return ("");
}

/*
 * Create a structured format representing files, folders, and their parents.
 */
function recursive_dir($thisDirectory, $seed, $parent)
{
	$show_images = true;
	$show_css = true;
	$show_scripts = true;

	if ($directoryId = opendir($thisDirectory))
	{
		while (false !== ($thisFile = readdir($directoryId)))
		{
			if (
			    ($thisFile != ".") && 
			    ($thisFile != "..") && 
			    ($thisFile != ".DS_Store") && 
			    (substr($thisFile, -5) != ".orig")
			)
			{
				$show_image  = is_image($thisFile)  ? $show_images  : true;
				$show_css    = is_css($thisFile)    ? $show_css     : true;
				$show_script = is_script($thisFile) ? $show_scripts : true;
				if ($show_image && $show_css && $show_script)
				{
					$seed++;
					print_r("$seed\t$parent\t$thisFile\t");
					if (is_dir($thisDirectory.$thisFile))
					{
						print_r("1\t\n");
						recursive_dir($thisDirectory.$thisFile."/", $seed, $seed);
					}
					else
					{
						$title = '';
						if ( (substr($thisFile, -5) == ".html") || (substr($thisFile, -4) == ".htm") )
						{
							$html = file_get_contents($thisDirectory.$thisFile);
							$title = get_title($html);
							$title = unhtmlentities($title);
						}
						print_r("0\t$title\n");
					}
				}
			}
		}
		closedir($directoryId);
	}
}

/*
 *
 */
function is_image ($file)
{
    $is_image = (
        (substr($file, -4) == ".jpg") || 
        (substr($file, -4) == ".gif") || 
        (substr($file, -4) == ".png") || 
        (substr($file, -5) == ".jpeg")
    );
    return $is_image;
}

/*
 *
 */
function is_css ($file)
{
    $is_css = (substr($file, -4) == ".css");
	return $is_css;
}

/*
 *
 */
function is_script ($file)
{
	$is_script = (substr($file, -3) == ".js");
	return $is_script;
}

/*
 * This is based on http://urlgreyhot.com/graphviz/
 */
function create_dot_file($source)
{
	global $outfile;
	$dotlines = "\n";
	$lines = explode("\n", $source);
	for ($i = 0; $i < count($lines); $i++)
	{
		$line = $lines[$i];
		$items = explode("\t", $line);
		$id = rtrim($items[0]);
		$parent_id = rtrim($items[1]);
		$filename = addslashes(rtrim($items[2]));
		$is_directory = rtrim($items[3]);
		$html_title = rtrim($items[4]);
		
		if ($html_title)
		{
			$label = "$html_title\\n$filename";
		}
		else
		{
			$label = $filename;
		}
		
		if ($id != '')
		{
			$dotlines .= "\n\t$id [label=\"$label\"";
			if ($is_directory == '1')
			{
				$dotlines .= ', fontname="GillSans-Bold", fillcolor="#f7f7f7"';
			}
			if ($id == 0)
			{
				$dotlines .= ', fontname="GillSans-Bold", fillcolor="#f7f7f7", shape="circle"';
			}              
			$dotlines .= "];\n";
		}
		if ($id != $parent_id)
		{
			$dotlines .= "\t$parent_id -> $id;\n";
		}
	}

	$dotsource = "/*\n * generated by folder2dot.app\n */\n";
	$dotsource .= "digraph G\n{\n";
	$dotsource .= '	graph [rankdir=LR, fontcolor="#7e7e7e", fontname=GillSans, fontsize="12.00", labeljust=l, labelloc=t];' . "\n";
	$dotsource .= '	node [color="#7e7e7e", fillcolor="#ffffff", fontname=GillSans, fontsize="10.00", shape=box, style=filled, width="2.00"];' . "\n";
	$dotsource .= '	edge [arrowhead=none, color="#7e7e7e", fontcolor="#7e7e7e", fontname=GillSans, fontsize="10.00"];';
	$dotsource .= $dotlines;
	$dotsource .= "}";
	
	$fhout = fopen($outfile, 'w');
	fwrite($fhout, $dotsource);
	fclose($fhout);
}

/*
 * Return the value of a html fragment's <title> tag
 */
function get_title ($html)
{
	$regex = '/\<title\>(.*)\<\/title\>/si';
	$got_title = preg_match($regex, $html);
	if ($got_title)
	{
		$title_fragment = preg_split($regex, $html, -1, PREG_SPLIT_DELIM_CAPTURE);
		$title = trim ($title_fragment[1]);
	}
	else
	{
		$title = '';
	}
	return $title;
}

/*
 * This is here because PHP's html_entity_decode wasn't decoding &ndash; and &mdash;
 */
function unhtmlentities($string)
{
   $trans_tbl = get_html_translation_table(HTML_ENTITIES);
   $trans_tbl = array_flip($trans_tbl);
   $trans_tbl['&ndash;'] = '-';
   $trans_tbl['&mdash;'] = '-';
   return strtr($string, $trans_tbl);
}